from APKManager.apps import ApkmanagerConfig
from .models import *
from .errcode import *
from Common.utils import *


class Helper(object):
    @staticmethod
    def authenticate(username, password):
        wbact = model_find(WbUser, username=username)
        if not wbact:
            raise errUserNotFound
        if not wbact.active:
            raise errUserIsNotActive

        md5pwd = hashlib.md5()
        md5pwd.update(password)
        if md5pwd.hexdigest() != wbact.password:
            raise errInvalidUserNameOrPassword

        return wbact

    @staticmethod
    def upload_file(user, files):
        def _save_file(path, f):
            with open(path, "wb+") as fp:
                for chunk in f.chunks():
                    fp.write(chunk)

        path_list = []
        udir = "%s/%s" % (ApkmanagerConfig.upload_to, user.account)
        # if the user directory does not exist.
        if not os.path.exists(udir):
            try:
                os.mkdir(udir)
            except:
                raise errSystemException

        for f in files:
            path = "%s/%s" % (udir, f.name)
            try:
                _save_file(path, f)
                path_list.append(path)
            except Exception as e:
                logging.error("can not save file due to %s." % (str(e)))
                raise errSystemException

        return path_list

    @staticmethod
    def save_supplier(user, **info):
        supplier = model_find(WbSupplier,
                              user=user)

        if supplier:
            if not supplier.status.name in ("Normal", "Rejected"):
                raise errPermissionDenied
        else:
            role = role_model.get_item(info.get('type'))
            no = WbAutoNo.newNo(role.key)
            status = status_model.get_item("Normal")
            supplier = model_create(WbSupplier,
                                    user=user,
                                    role=role,
                                    no=no,
                                    company_info=model_create(WbCompanyInfo),
                                    finance_info=model_create(WbFinanceInfo),
                                    contact_info=model_create(WbContactInfo),
                                    status=status)

        model_set(supplier.company_info, **info)
        model_set(supplier.finance_info, **info)
        model_set(supplier.contact_info, **info)

        return supplier

    @staticmethod
    def make_query_sql(table, limit=0, offset=0, orderby=None, desc=False, **conditions):
        sql = "SELECT * FROM {0}".format(table)
        if conditions:
            sql += " WHERE "
            for k in conditions.keys():
                if isinstance(conditions[k], str):
                    sql += " {0}=\"{1}\" ".format(k, conditions[k])
                else:
                    sql += " {0}=\"{1}\" ".format(k, conditions[k])
                if conditions.keys()[-1] != k:
                    sql += "AND"

        if orderby:
            sql += " ORDER BY {0}".format(orderby)
            if desc:
                sql += " DESC"

        if limit > 0:
            sql += " LIMIT {0}".format(limit)

        if offset > 0:
            sql += " OFFSET {0}".format(offset)

        return sql

    @staticmethod
    def query_suppliers(limit, offset, orderby=None, desc=False, **conds):
        try:
            sql = Helper.make_query_sql("wb_supplier", limit, offset, orderby, desc, **conds)
            return WbSupplier.objects.raw(sql)
        except:
            return None